<template>
  <el-container direction="vertical">
    <BaseHeader />
    <ElMain>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="card">
            <div class="avatar"  @click="editAvatar">
              <el-avatar :size="100" :src="userInfo.avatar"></el-avatar>
            </div>
            <div class="user-info">
              <h2>
                {{ userInfo.name }}
                <el-icon class="edit-icon" @click="editUserInfo('name')"><Edit /></el-icon>
              </h2>
              <p>
                {{ userInfo.bio }}
                <el-icon class="edit-icon" @click="editUserInfo('bio')"><Edit /></el-icon>
              </p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="card">
            <h3>已发布作品</h3>
            <div>
              <el-card shadow="hover" class="card-post" v-for="(work, index) in publishedWorks" :key="index">
                <ul>
                  <li>
                    <h4>{{ work.title }}</h4>
                    <p>{{ work.description }}</p>
                  </li>
                </ul>
              </el-card>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="card">
            <h3>已点赞的作品</h3>
            <div>
              <el-card shadow="hover" class="card-post" v-for="(work, index) in likedWorks" :key="index">
                <ul>
                  <li>
                    <h4>{{ work.title }}</h4>
                    <p>{{ work.description }}</p>
                  </li>
                </ul>
              </el-card>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </ElMain>
    <el-dialog v-model="isEdit" title="修改头像" width="600px">
      <div v-if="!imageSrc">
        <el-upload
          class="avatar-uploader"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
        >
          <el-button type="primary">选择图片</el-button>
        </el-upload>
      </div>
      <div v-else class="cropper-container">
        <div class="cropper-wrap">
          <vue-cropper
            ref="cropper"
            :img="imageSrc"
            :outputSize="1"
            :outputType="'png'"
            :info="true"
            :full="true"
            :canMove="true"
            :canMoveBox="true"
            :original="false"
            :autoCrop="true"
            :autoCropWidth="200"
            :autoCropHeight="200"
            :fixedBox="true"
            @realTime="cropImage"
            @imgLoad="isCropperReady = true"
          ></vue-cropper>
        </div>
        <div class="preview-container">
          <img v-if="previewUrl" :src="previewUrl" alt="预览" class="preview-img" />
        </div>
      </div>
      <div v-if="imageSrc" class="cropper-buttons">
        <el-button @click="rotateImage(1)">向左旋转</el-button>
        <el-button @click="rotateImage(0)">向右旋转</el-button>
        <el-button @click="resetImage">重置</el-button>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="confirmCrop" :disabled="!imageSrc">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加用户信息编辑对话框 -->
    <el-dialog v-model="isEditingInfo" :title="editingField === 'name' ? '修改昵称' : '修改简介'">
      <el-input
        v-model="editingValue"
        :placeholder="editingField === 'name' ? '请输入新昵称' : '请输入新简介'"
        :type="editingField === 'bio' ? 'textarea' : 'text'"
      ></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isEditingInfo = false">取消</el-button>
          <el-button type="primary" @click="confirmEditInfo">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
import BaseHeader from '@/components/common/BaseHeader.vue';
import { ElMain, ElContainer, ElCard, ElRow, ElCol, ElDialog, ElUpload, ElButton, ElAvatar, ElIcon, ElInput } from 'element-plus';
import { Edit } from '@element-plus/icons-vue';
import { ref } from 'vue';
import { VueCropper } from 'vue-cropper';
import 'vue-cropper/dist/index.css';

const userInfo = ref({
  name: '张三',
  bio: '这是个人简介。',
  avatar: '/src/assets/avatar.png'
});

const publishedWorks = ref([
  { title: '作品1', description: '这是作品1的描述。' },
  { title: '作品2', description: '这是作品2的描述。' },
  { title: '作品3', description: '这是作品3的描述。' },
  { title: '作品3', description: '这是作品3的描述。' },
  { title: '作品3', description: '这是作品3的描述。' },
  { title: '作品3', description: '这是作品3的描述。' },
  { title: '作品3', description: '这是作品3的描述。' }
]);

const likedWorks = ref([
  { title: '作品A', description: '这是作品A的描述。' },
  { title: '作品B', description: '这是作品B的描述。' }
]);

const isEdit = ref(false);
const imageSrc = ref('');
const cropper = ref<InstanceType<typeof VueCropper> | null>(null);
const isCropperReady = ref(false);
const previewUrl = ref('');
const isImageLoaded = ref(false);

const isEditingInfo = ref(false);
const editingField = ref<'name' | 'bio'>('name');
const editingValue = ref('');

const editAvatar = () => {
  isEdit.value = true;
};

const handleFileChange = (file: any) => {
  const reader = new FileReader();
  reader.onload = (e: any) => {
    imageSrc.value = e.target.result;
  };
  reader.onerror = (e) => {
    console.error('图片加载失败:', e);
  };
  reader.readAsDataURL(file.raw);
};

const rotateImage = (type: number) => {
  if (cropper.value) {
    if (type == 1) {
      cropper.value.rotateLeft();
    } else {
      cropper.value.rotateRight();
    }
  }
};

const resetImage = () => {
  if (cropper.value) {
    cropper.value.refresh();
  }
};

const cropImage = () => {
  if (cropper.value && isCropperReady.value) {
    cropper.value.getCropData((data: string) => {
      previewUrl.value = data;
    });
  }
};

const confirmCrop = () => {
  if (cropper.value) {
    cropper.value.getCropData((data: string) => {
      userInfo.value.avatar = data;
      isEdit.value = false;
      imageSrc.value = '';
      // 这里应该调用一个方法来更新用户的头像到服务器
      updateUserAvatar(data);
    });
  }
};

const cancelEdit = () => {
  isEdit.value = false;
  imageSrc.value = '';
};

const updateUserAvatar = (avatarData: string) => {
  // 这里应该实现一个方法来更新用户的头像到服务器
  console.log('Updating user avatar with data:', avatarData);
};

const editUserInfo = (field: 'name' | 'bio') => {
  editingField.value = field;
  editingValue.value = userInfo.value[field];
  isEditingInfo.value = true;
};

const confirmEditInfo = () => {
  userInfo.value[editingField.value] = editingValue.value;
  isEditingInfo.value = false;
  // 这里应该调用一个方法来更新用户信息到服务器
  updateUserInfo(editingField.value, editingValue.value);
};

const updateUserInfo = (field: string, value: string) => {
  // 这里应该实现一个方法来更新用户信息到服务器
  console.log(`Updating user ${field} with value:`, value);
};
</script>

<style lang="scss" scoped>
.card {
  height: 375px;
  display: flex;
  flex-direction: column;
  overflow: scroll;
  padding-right: 10px;
}

.card-post {
  margin-bottom: 10px;
}

h3 {
  margin-bottom: 10px;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  margin-bottom: 10px;
}

.avatar {
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
  cursor: pointer;
}

h2 {
  text-align: center;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.cropper-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cropper-wrap {
  width: 300px;
  height: 300px;
}

.preview-container {
  width: 200px;
  height: 200px;
  overflow: hidden;
  border: 1px solid #ccc;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cropper-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>